# -*- coding: utf-8 -*-
# @Time: 2025/9/29 0:46
# @Author: foxhuty
# @File: users.py
from logging import exception

from fastapi import APIRouter
from markdown_it.common.html_re import attribute
import sqlalchemy
from models.users import User
from models import AsyncSessionFactory
from schemas.users import UserCreateRequestSchema, UserCreateResponseSchema
from fastapi.exceptions import HTTPException

data: dict={
        "email": "foxhuty@foxhuty.com",
        "username": "foxhuty",
    }

router = APIRouter(prefix="/user", tags=["user"])
@router.post("add/",response_model=UserCreateResponseSchema)
async def add_user(user_data: UserCreateRequestSchema):
    session = AsyncSessionFactory()
    try:
        user = User(
            email=user_data.email,
            username=user_data.username,
            password=user_data.password
        )
        session.add(user)
        await session.commit()
        await session.refresh(user, attribute["id"])
    except sqlalchemy.exc.IntegrityError as e:
        print(e)
        await session.rollback()
        raise HTTPException(status_code=400, detail="Email or username already exists")
    await session.close()
    return user

